<?php
session_start();
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/class.user.php');
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/database.php');
$cachekey="NUM-LOGIN-ATTEMPTS-".$_SERVER['REMOTE_ADDR'];
$mc = new Memcached();
$mc->addServer('localhost', 11211);	
$j=$mc->get($cachekey);

if($j===FALSE) {
	$attmepts=0;
} else {
	$attempts=$j;
}
if($attempts>=5) {
	echo("<script>\$.fn.message('show','<div class=\"error_h_message\"><h2>Error</h2><p><strong>You have used the maximum number of attempts when trying to authenticate. Your account has now been locked for one hour.</strong></p></div>');</script>");
	exit("DIE");	
}
$attempts++;
$mc->set($cachekey, $attempts, 3600);
// memcache the num of requests in the hour - on IP ?
if( strtolower($_POST['security_code']) != strtolower($_SESSION['rand_code']) ) {
	
	
	echo("<script>\$.fn.message('show','<div class=\"error_h_message\"><h2>Error</h2><p><strong>Security Code is incorrect</strong></p></div>');</script>");
	exit("Security Code is incorrect");	
	
}
 
if(	strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])	 != 'xmlhttprequest'	) {
	exit("I don't think so kid.");	
}
$username=$_POST['username'];
$password=$_POST['password'];

if(empty($username)) {
	echo("<script>\$.fn.message('show','<div class=\"error_h_message\"><h2>Error</h2><p><strong>Username cannot be empty</strong></p></div>');</script>");
	exit("Username cannot be empty");	
}
if(empty($password)) {
		echo("<script>\$.fn.message('show','<div class=\"error_h_message\"><h2>Error</h2><p><strong>Password cannot be empty</strong></p></div>');</script>");

	exit("Password cannot be empty");	
}
$mc->set($cachekey, 0, 3600);

$user=new user();
$data=new database();
$data->db(DATABASE)->collection('users');
$data->criteria(array('username'=>$username));
$row=$data->findOne();
if($password!=$user->decrypt($row['password'],CRYPT_KEY)) {
		echo($user->decrypt($password,CRYPT_KEY));
		echo("<script>\$.fn.message('show','<div class=\"error_h_message\"><h2>Error</h2><p><strong>You could not be authenticated</strong></p></div>');</script>");

	exit("You could not be authenticated");	
	
}
$user->init_user((string)$row['_id']);
$data=new database();
$data->db(DATABASE)->collection('users');
$data->criteria(array('$set'=>array('last_login'=>intval(time()))));
$data->update();

if($_SESSION['admin']==1) {
	exit("<script>document.location.href='/admin/';</script>");	
} else {
	exit("<script>document.location.href='/';</script>");	
}



?>